package com.test.ayi.service;

import com.test.ayi.mapper.UserMapper;
import com.test.ayi.model.User;
import com.test.ayi.util.MultiLevelCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

/**
 * 用户服务实现
 *
 * @author hxstrive.com
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private MultiLevelCache multiLevelCache;

    private static final String USER_CACHE_PREFIX = "user:name:";
    private static final long USER_CACHE_EXPIRE = 3600; // 1小时

    @Override
    public User getUserByName(String username) {
        String cacheKey = USER_CACHE_PREFIX + username;
        return (User) multiLevelCache.getWithMultiLevel(
            cacheKey,
            key -> userMapper.selectUserByUserName(username),
            USER_CACHE_EXPIRE
        );
    }

    @Override
    public void saveUser(User user) {
        userMapper.insert(user);
        // 更新缓存
        String cacheKey = USER_CACHE_PREFIX + user.getUsername();
        multiLevelCache.put(cacheKey, user, USER_CACHE_EXPIRE);
    }
}